<template>
  <div class="resource-download-container">
    <nav v-if="categories.length > 0" class="category-nav-container">
      <ul class="category-nav">
        <li
            @click="filterByCategory(null)"
            class="all-resources"
            :class="{ active: currentCategory === null }"
        >
          全部
        </li>
        <li
            v-for="category in categories"
            :key="category.id"
            @click="filterByCategory(category.id)"
            :class="{ active: currentCategory === category.id }"
        >
          {{ category.name || '默认分类' }}
        </li>
      </ul>
    </nav>
    <div class="resource-content">
      <div v-if="filteredResources.length === 0" class="no-resources">
        <i class="fa fa-exclamation-circle"></i> 暂无资源。
      </div>
      <div class="resource-card" v-for="resource in filteredResources" :key="resource.id">
        <img
            :src="resource.image || 'https://picsum.photos/160/160'"
            alt="Resource Image"
            class="resource-image"
            @error="handleImageError"
        />
        <h3 class="resource-title">{{ resource.title }}</h3>
        <p class="resource-description">{{ resource.content }}</p>
        <div class="resource-meta">
          <span><i class="fa fa-tag" style="margin-right: 5px;"></i>{{ resource.category.name || '默认分类' }}</span>
          <span><i class="fa fa-user" style="margin-right: 5px;"></i>{{ resource.author || '匿名' }}</span>
        </div>
        <div class="resource-actions">
          <!-- 预览按钮 -->
          <button v-if="resource.article" class="action-button" @click="previewResource(resource)">
            <i class="fa fa-eye"></i> 演示
          </button>
          <button
              v-if="resource.file && !resource.article"
              class="action-button"
              @click="previewResource(resource)"
          >
            <i class="fa fa-eye"></i> 预览
          </button>

          <!-- 下载按钮 -->
          <button class="action-button" @click="downloadResource(resource)">
            <i class="fa fa-download"></i> 下载
          </button>
        </div>
      </div>
      <div :class="['loading-container', { show: loading }]">
        <i class="fa fa-spinner fa-spin"></i> 加载中...
      </div>
    </div>
    <ArticlePagination
        :currentPage="currentPage"
        :page_size="pageSize"
        :totalItems="totalItems"
        :totalPages="totalPages"
        @page-change="handlePageChange"
    />
  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue'
import {useRouter} from 'vue-router'
import {useUserStore} from '@/stores/userStore.js'
import ArticlePagination from "@/components/articles/ArticlePagination.vue";
import axios from 'axios';

const store = useUserStore()
const router = useRouter()
// 响应式状态
const categories = ref([])
const allResources = ref([])
const filteredResources = ref([])
const currentCategory = ref(null)
const loading = ref(false)
// 页码相关
const currentPage = ref(1)
const pageSize = ref(10) // 每页条数
const totalPages = ref(0) // 总页数
const totalItems = ref(0) // 总条数

// 方法
const fetchCategoriesAndResources = async (page = 1) => {
  loading.value = true
  try {
    const [categoryRes, resourceRes] = await Promise.all([
      axios.get('/api/resources/download/categories/'),
      axios.get('/api/resources/download/', {
        params: {
          preview: true,
          page: page,
          category: currentCategory.value
        }
      })
    ])

    categories.value = categoryRes.data
    allResources.value = resourceRes.data.results
    pageSize.value = resourceRes.data.page_size
    currentPage.value = resourceRes.data.page
    totalPages.value = resourceRes.data.total_pages
    totalItems.value = resourceRes.data.count
    filteredResources.value = [...allResources.value]
  } catch (error) {
    console.error('获取数据失败:', error)
  }
  loading.value = false
}

const filterByCategory = (categoryId) => {
  currentCategory.value = categoryId
  fetchCategoriesAndResources();
}

const downloadResource = async (resource) => {
  try {
    // 使用resource.file作为下载URL
    const response = await fetch(resource.file, {
      headers: new Headers({
        'Authorization': `Bearer ${store.authToken}` // 携带认证信息
      })
    })

    if (!response.ok) {
      throw new Error(`下载失败：${response.status} ${response.statusText}`)
    }

    // 从响应头获取文件名
    const contentDisposition = response.headers.get('content-disposition')
    let filename = ''

    if (contentDisposition) {
      filename = contentDisposition.split('filename=')[1].replace(/"/g, '')
    } else if (resource.file) {
      filename = resource.file.split('/').pop()
    } else {
      filename = `download_${Date.now()}`
    }

    // 确保文件名包含扩展名
    const blob = await response.blob()
    const url = window.URL.createObjectURL(blob)

    // 如果文件名没有扩展名，则使用resource.file的扩展名
    if (!filename.includes('.')) {
      filename += '.' + resource.file.split('.').pop()
    }

    const link = document.createElement('a')
    link.href = url
    link.download = decodeURIComponent(filename) // 处理中文文件名
    link.style.display = 'none'

    document.body.appendChild(link)
    link.click()

    // 清理对象URL
    setTimeout(() => {
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
    }, 100)
  } catch (error) {
    console.error('下载失败:', error)
    alert(error.message)
  }
}

const previewResource = (resource) => {
  const getFileExtension = (url) => {
    if (!url) return 'unknown';
    try {
      const cleanUrl = url.split(/[#?]/)[0];
      const path = new URL(cleanUrl).pathname;
      const extension = path.split('.').pop() || 'unknown';
      return extension.toLowerCase();
    } catch {
      const parts = url.split('.');
      return parts.length > 1 ? parts.pop().toLowerCase() : 'unknown';
    }
  }

  const fileType = getFileExtension(resource.file);

  const nativelySupported = ['pdf', 'png', 'jpg', 'jpeg', 'gif', 'webp', 'txt']
  const documentTypes = ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'csv']

  if (nativelySupported.includes(fileType)) {
    window.open(resource.file, '_blank')
  } else if (documentTypes.includes(fileType)) {
    window.open(`https://view.officeapps.live.com/op/view.aspx?src=${encodeURIComponent(resource.file)}`)
  } else if (resource.article) {
    router.push({name: 'article-detail', params: {id: resource.article.id}})
  } else {
    alert(`不支持预览 ${fileType.toUpperCase()} 格式文件，请下载后查看`)
  }
}

const handleImageError = (event) => {
  event.target.src = 'https://via.placeholder.com/150';
}

const handlePageChange = (newPage) => {
  currentPage.value = newPage;
  fetchCategoriesAndResources(newPage);
}

onMounted(() => {
  fetchCategoriesAndResources()
})
</script>


<style scoped>
.resource-download-container {
  width: 100%;
  min-height: 100vh;

}

.category-nav-container {
  background-color: var(--resources-bg-color, #fff);
}

.category-nav {
  list-style-type: none;
  padding: 0;
  margin-top: 10px;
  display: flex;
  justify-content: center;
  width: 100%;
}

.category-nav li {
  margin: 0 15px;
  padding: 6px 10px;
  cursor: pointer;
  color: var(--resources-link-color, #3498db);
  font-weight: bold;
  border-bottom: 2px solid transparent;
}

.category-nav li:hover {
  background-color: var(--resources-link-hover-color, #f2f2f2);
  color: var(--resources-link-hover-text-color, #3498db);
}

.category-nav li.active {
  color: var(--resources-active-hover-text-color, #5fb878);
  border-bottom: 2px solid var(--resources-active-hover-color, #5fb878);
}


.resource-content {
  margin-top: 20px;
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 10px;
}

.resource-card {
  background-color: var(--resources-bg-color, #fff);
  border-radius: 8px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  padding: 10px;
  text-align: center;
}

.resource-card:hover {
  box-shadow: 0 8px 12px rgba(0, 0, 0, 0.1);
}

.resource-image {
  width: 100%;
  height: 135px;
  object-fit: cover;
}


.resource-title {
  font-size: 18px;
  color: var(--resources-link-color, #3498db);
}

.resource-title:hover {
  color: var(--resources-link-hover-color, #5fb878);
}

.resource-description {
  font-size: 12px;
  color: var(--resources-desc-color, #777);
  margin: 5px 0 8px 0;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
}

.no-resources {
  text-align: center;
  align-items: center;
  justify-content: center;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 1rem;
}

.resource-meta {
  font-size: 14px;
  color: var(--resources-meta-color, #aaa);
  margin: 10px 0;
}

.resource-meta span {
  margin-right: 10px;
}

.resource-actions {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

.action-button {
  padding: 2px 4px;
  margin: 0 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: var(--resources-button-download-bg-color, #fff);
  color: var(--resources-button-download-color, #5fb878);
  cursor: pointer;
}

.action-button:hover {
  background-color: var(--resources-button-download-color, #5fb878);
  color: var(--resources-button-download-bg-color, #fff);
}

.loading-container {
  opacity: 0;
  transition: opacity 0.3s ease;
}

.loading-container.show {
  opacity: 1;
}


@media (max-width: 992px) {
  .category-nav li {
    margin: 0 10px;
  }

  .resource-content {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 576px) {
  .resource-content {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 400px) {
  .resource-content {
    grid-template-columns: repeat(1, 1fr);
  }
}
</style>
